﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Services;
using System.Text;

namespace Janus.Cores.RealProxy
{
    public class IdalProxy : System.Runtime.Remoting.Proxies.RealProxy
    {
        private readonly MarshalByRefObject target;

        public IdalProxy(MarshalByRefObject obj, Type type) : base(type)
        {
            this.target = obj;
        }
                
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage call = (IMethodCallMessage)msg;
            //如果触发的是构造函数，此时target的构建还未开始
            IConstructionCallMessage ctor = call as IConstructionCallMessage;
            if (ctor != null)
            {
                System.Console.WriteLine("转发构造函数调用！");
                System.Runtime.Remoting.Proxies.RealProxy default_proxy = RemotingServices.GetRealProxy(this.target); //因为远端对象也是在本地，故也要用透明代理去调用实际操作？
                default_proxy.InitializeServerObject(ctor);
                MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy();
                return EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);
            }

            System.Console.WriteLine("预处理中......");
            System.Threading.Thread.Sleep(1000);
            IMethodReturnMessage result_msg = RemotingServices.ExecuteMessage(this.target, call);
            System.Console.WriteLine("后处理中......");
            System.Threading.Thread.Sleep(1000);
            System.Console.WriteLine("后处理结束！");
            return result_msg;
        }
    }
}
